<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="search-form divClass" v-if="headerShow">
                <div>
                    <a-form size="small" :model="pageData" layout="inline" style="margin-top:20px">
                        <a-form-item label="配方单号">
                            <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                                v-model="pageData.dropDownData" @press-enter="huiche" />
                        </a-form-item>
                    </a-form>
                </div>
                <div class="my-tool-bar">
                    <Toolbar style="float:right" v-if="id == 1" :items="['查询', '删除', '审核', '导入中控']" @add="addHandler"
                        @import="importHandler" @del="deleteHandler" @select="selectHandler" @export="exports"
                        @audit="audits">
                    </Toolbar>
                </div>
            </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                    <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
        </template>
        <template #pageTabel>
            <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:99%;width: 100%;z-index:999 ;">
                <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressDragLeaveHidesColumns="true"
                    :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady" style="height:100%"
                    :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="table.dataList" :columnDefs="tc"
                    :localeText="localeText1" @columnResized="onColumnResized01" @columnMoved="onColumnMoved01"></AgGridVuesCopys>
            </a-spin>
        </template>
        <paginationCopys :page-size-options="pagingList1" :page-size="size" :current="page" :total="total" show-total
            show-jumper show-page-size @change="PageSize" @page-size-change="change1" style="justify-content: center" />
        <a-drawer ok-text='保存' cancel-text='关闭' :drawer-style="{ 'zIndex': 9999 }" :mask-closable="false" :width="400"
            :ok-loading="pageData.pageLoading" :visible="pageData.showAdd" unmountOnClose @ok="sideOk"
            @cancel="pageData.showAdd = false">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
        </a-drawer>
    </pageTabelLayout>
</template>

<script lang="ts">
import { pagingList } from "@/api/paging";
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table';
import emitter from "@/hooks/useEventBus";
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue';
import { Form, Message, Modal } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { baseURL } from '../../../api/axios.config'
import axios from "axios";
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue';
import { AnyARecord } from 'dns';

import { localeText } from '@/api/aggridZw'
import WHService, { Warhouse, CompanyList, WhTypeField } from '@/service/wh'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
import { saveOrUpdateGridState as saveOrUpdateGridState02 } from '@/hooks/useGridState'


interface BrandInfo {
    "id": any,
    "remark": any,
    "createName": string | undefined,
    "createTime": string | undefined,
    "updateName": string | undefined,
    "updateTime": string | undefined,
    "deleteState": any,
    "obsoleteState": any,
    "serialNumber": any,
    "materialName": any,
    "materialCode": any,
    "foremanTechnology": any,
    "straight": any,
    "bathe": any,
    "maxValues": any,
    "hACacidity": any,
    "stockNumber": any,
    "jobType": any,
}

export default {
    name: "ImportCentralCheckpoint",
    setup() {
        const total = ref(10);
        const page = ref(1);
        const size = ref(10);
        function PageSize(val: any) {
            page.value = val
            doRefresh();
        }
        function change1(val: any) {
            size.value = val
            doRefresh();
        }
        const headerShow = ref<boolean>(true)
        //查询方法
        function doRefresh() {
            pageData.pageLoading = true
            // updateGridState01()
            post({
                url: "/pdm/TransitInspect/selectPage",
                data: {
                    page: page.value,
                    size: size.value,
                    deleteState: "0",
                    formulaOdd: pageData.dropDownData
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        table.handleSuccess(data.list);
                        gridOption.value.setRowData(data.list);
                        total.value = data.total;
                        gridOption.value.sizeColumnsToFit();
                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })

        }
        // 定义从主表获取过来的数据
        let keyList = {
            formulaOdd: '',
            flowCardCode: '',
            property: '',
        }
        function doRefresh2() {
            pageData.pageLoading = true
            updateGridState02()
            post({
                url: "/pdm/TransitInspect/selectPage",
                data: {
                    page: pagination.page,
                    size: pagination.pageSize,
                    deleteState: 0,
                    auditState: 1,
                    formulaOdd: pageData.dropDownData
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        table.handleSuccess(data.list);
                        gridOption2.value.setRowData(data.list);
                        total.value = data.total;
                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })
            // pageData.pageLoading = true
            // post({
            //     url: "/pdm/TransitInspect/selectPage",
            //     data: {
            //         // "page": page.value,
            //         // "size": size.value,
            //         // deleteState: "0",
            //         formulaOdd:keyList.formulaOdd
            //     },
            // })
            //     .then(({ data, code }: any) => {
            //         if (code === 200) {
            //             table.handleSuccess(data.list);
            //             gridOption2.value.setRowData(data.list);
            //             total.value = data.total;
            //         }
            //     })
            //     .catch(console.log).finally(() => {
            //         pageData.pageLoading = false
            //     })

        }
        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        const tableColumns1 = useTableColumn([
            {
                title: "配方单号",
                key: "formulaOdd",
                dataIndex: "formulaOdd",
                width: 160,
            },
            {
                title: "中转站时间",
                key: "transferDate",
                dataIndex: "transferDate",
                width: 160
            },
            {
                title: "流转卡号",
                key: "flowCardCode",
                dataIndex: "flowCardCode",
                width: 160
            },
            {
                title: "性质",
                key: "property",
                dataIndex: "property",
                width: 160
            }
        ]);
        const tableColumns2 = useTableColumn([
            {
                title: "配方单号",
                key: "formulaOdd",
                dataIndex: "formulaOdd",
                width: 200,
            },
            {
                title: "中转站时间",
                key: "transferDate",
                dataIndex: "transferDate",
                width: 200
            },
            {
                title: "中控审核时间",
                key: "auditStateDate",
                dataIndex: "auditStateDate",
                width: 200
            },
            {
                title: "流转卡号",
                key: "flowCardCode",
                dataIndex: "flowCardCode",
                width: 200
            },
            {
                title: "性质",
                key: "property",
                dataIndex: "property",
                width: 160
            },
            {
                title: "工艺1",
                key: "craftOne",
                dataIndex: "craftOne",
                width: 150
            },
            {
                title: "工艺2",
                key: "craftTwo",
                dataIndex: "craftTwo",
                width: 150
            },
            {
                title: "工艺3",
                key: "craftThree",
                dataIndex: "craftThree",
                width: 150
            },
            {
                title: "工艺4",
                key: "craftFour",
                dataIndex: "craftFour",
                width: 150
            },
            {
                title: "工艺5",
                key: "craftFive",
                dataIndex: "craftFive",
                width: 200
            },
            {
                title: "工艺6",
                key: "craftSix",
                dataIndex: "craftSix",
                width: 150
            },
            {
                title: "工艺7",
                key: "craftSeven",
                dataIndex: "craftSeven",
                width: 200
            },
            {
                title: "工艺8",
                key: "craftEight",
                dataIndex: "craftEight",
                width: 200
            },
            {
                title: "设备编号",
                key: "machineOdd",
                dataIndex: "machineOdd",
                width: 200
            },
        ]);
        let tc: any[] = tableColumns1.map((o) => {
            let obj = {
                headerName: o.title,
                field: o.key,
                pinned: o['fixed']
            }
            return obj
        })
        let tc2: any[] = tableColumns2.map((o) => {
            let obj = {
                headerName: o.title,
                field: o.key,
                pinned: o['fixed']
            }
            return obj
        })
        let a = [{
            showRowGroup: 'hide_def',
            "headerName": "",
            "checkboxSelection": true,
            "headerCheckboxSelection": true,
            "pinned": "left",
            "width": 60,
            resizable: false,
            filter: false,
            sortable: false,
            minWidth: 60,
            maxWidth: 60,
            lockPosition: "left",
        }]
        tc = a.concat(tc)
        tc2 = a.concat(tc2)

        const pageData = reactive<{
            showAdd: boolean,
            sideTitle: string,
            dropDownData: any,
            nameList: [],
            pageLoading: boolean,
            typeList: [],
            dropDownData1: any,
            rHeight: any,
            btnList: any[],
            isEdit: boolean,
            wlList: [],
            isLxs: boolean,
            CodeNameList: [],
            bgNameList: any[],
            dutymachineState: number | undefined,
        }>({
            nameList: [],
            showAdd: false,
            sideTitle: '新增导入中控中转检查站',
            dropDownData: "",
            pageLoading: false,
            typeList: [],
            dropDownData1: "",
            rHeight: 0,
            btnList: [],
            isEdit: false,
            wlList: [],
            isLxs: false,
            CodeNameList: [],
            bgNameList: [],
            dutymachineState: 0,
        });

        interface gcType {
            id: any,
            company: any,
        }
        //下拉框得到焦点
        const focusSel = () => {
            selCxAll({ formulaOdd: "" });
        }
        //下拉数据 
        const options = ref<any>(pageData.nameList);
        const loading = ref(false);
        const handleSearch = (value: any) => {
            if (value) {
                const ob = { formulaOdd: value, deleteState: 0 }
                loading.value = true;
                selCxAll(ob);
                options.value = pageData.nameList;
                loading.value = false;
            } else {
                options.value = []
            }
        };
        //下拉框查询
        function selCxAll(val: any) {
            post({
                url: "/pdm/TransitInspect/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    let dataList: any = [];
                    data.forEach(function (o: any) {
                        dataList.push(o["formulaOdd"])
                    });
                    pageData.nameList = dataList;
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 6000,
                    });
                }
            });
        }
        onMounted(() => {
            doRefresh();
            // 切换tap到本页面执行的方法
            emitter.on("ImportCentralCheckpoint", () => {
                doRefresh();
            })
        });

        let cxbl = {}
        //查询
        const selectHandler = () => {
            page.value = 1
            doRefresh()
        }
        const queryData = reactive({
            materialName: ""
        });
        const addHandler = () => {
            for (var key in dataForm) {
                if (key === "id") {
                    dataForm[key] = null;
                } else {
                    dataForm[key] = "";
                }
            }
            dataForm.straight = false
            pageData.showAdd = true
            pageData.sideTitle = '新增导入中控中转检查站'
        }
        const dataForm = reactive<BrandInfo>({
            "id": null,
            "remark": "",
            "createName": "",
            "createTime": "",
            "updateName": "",
            "updateTime": "",
            "deleteState": 0,
            "obsoleteState": "",
            "serialNumber": 0,
            "materialName": null,
            "foremanTechnology": "",
            "straight": false,
            "hACacidity": null,
            "bathe": null,
            "maxValues": null,
            "stockNumber": "",
            "materialCode": "",
            "jobType": "",
        })

        // 表格准备事件
        const gridOption = ref()
        const colState01 = ref()
        const gridReady = (params: any) => {
            gridOption.value = params.api
            colState01.value = params.columnApi
        }
        const gridOption2 = ref()
        const colState02 = ref()
        const gridReady2 = (params: any) => {
            gridOption2.value = params.api
            colState02.value = params.columnApi
        }
        const formRef = ref<FormInstance>()
        const sideOk = () => {
            formRef.value?.validate().then((err) => {
                if (!err) {
                    formRef.value?.validate().then((err) => {
                        if (!err) {
                            pageData.pageLoading = true;
                            if (pageData.sideTitle === "新增导入中控中转检查站") {
                                post({
                                    url: "/pdm/JobType/insert",
                                    data: [dataForm],
                                }).then((res: any) => {
                                    if (res.code === 200) {
                                        formRef.value?.resetFields();
                                        pageData.showAdd = false;
                                        Message.success({
                                            content: "新增成功",
                                            duration: 6000,
                                        });
                                    } else {
                                        Message.error({
                                            content: res.message,
                                            duration: 6000,
                                        });
                                    }
                                    doRefresh();
                                }).finally(() => {
                                    doRefresh();
                                    pageData.pageLoading = false
                                })
                            } else {
                                post({
                                    url: "/pdm/JobType/update",
                                    data: [dataForm],
                                }).then((res: any) => {
                                    if (res.code === 200) {
                                        formRef.value?.resetFields();
                                        pageData.showAdd = false;
                                        Message.success({
                                            content: "修改成功",
                                            duration: 6000,
                                        });
                                    } else {
                                        Message.error({
                                            content: res.message,
                                            duration: 6000,
                                        });
                                    }
                                    //doRefresh();
                                }).finally(() => {
                                    doRefresh();
                                    pageData.pageLoading = false
                                })
                            }
                        }
                    });
                }
            })
        }
        const deleteHandler = () => {
            if (gridOption.value.getSelectedRows().length === 0) {
                Message.error('请先勾选')
                return
            }
            Modal.confirm({
                title: '系统提示',
                content: '确认删除选中的数据?',
                onOk() {
                    pageData.pageLoading = true;
                    post({
                        url: '/pdm/TransitInspect/delete',
                        data: gridOption.value.getSelectedRows().map((o: any) => { return o.id })
                    }).then(({ code, data }: any) => {
                        if (code === 200) {
                            Message.success({
                                content: '删除成功',
                                duration: 6000
                            })
                            pagination.page = 1
                            doRefresh()
                        } else {
                            Message.error({
                                content: '修改失败',
                                duration: 6000
                            })
                        }
                    }).finally(() => {
                        pageData.pageLoading = false
                    });
                }
            })
        }
        const editHandler = (record: BrandInfo) => {
            //循环对象 赋值
            for (let key in record) {
                dataForm[key] = record[key]
            }
            if (dataForm.straight == 1) {
                dataForm.straight = true
            } else {
                dataForm.straight = false
            }
            pageData.sideTitle = '修改导入中控中转检查站'
            pageData.showAdd = true
        }
        //判断是否填写了中文
        const isChiese = (value: string, cb: Function) => {
            return new Promise<void>(resolve => {
                if (window.encodeURI(value).indexOf('%') !== -1) {
                    cb('填写的值只能是英文数字组合或英文，数字！')
                }
                resolve()
            })
        }
        //input离开焦点 将小写转大写
        const inputBlur = () => {

        }
        //导出
        const exports = () => {
            if (gridOption.value.getSelectedRows().length === 0) {
                Message.error('请先勾选');
                return
            } else {
                let idList: any = []
                gridOption.value.getSelectedRows().forEach(function (o: any) {
                    idList.push(o['id'])
                })
                //将表头拼接出来
                let head = "<th>序号</th><th>开头工艺</th><th>物料编码</th><th>物料名称</th><th>是否优先</th><th>最小值</th><th>最大值</th><th>HAC酸性用量</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>"
                //拿到当前表格数据与勾选的行做筛选

                let nowRow = table.dataList.filter(function (o) {
                    return (gridOption.value.getSelectedRows().map((o: any) => { return o.id })).indexOf(o["id"]) !== -1;
                })
                let body = "";
                nowRow.forEach(function (o) {
                    body += "<tr><td>" + o["id"] + "</td>";
                    body += "<td>" + (o["foremanTechnology"] == undefined ? "" : o["foremanTechnology"]) + "</td>";
                    body += "<td>" + (o["stockNumber"] == undefined ? "" : o["stockNumber"]) + "</td>";
                    body += "<td>" + (o["materialName"] == undefined ? "" : o["materialName"]) + "</td>";
                    body += "<td>" + (o["straight"] === 0 ? " " : "√") + "</td>";
                    body += "<td>" + (o["bathe"] == undefined ? "" : o["bathe"]) + "</td>";
                    body += "<td>" + (o["maxValues"] == undefined ? "" : o["maxValues"]) + "</td>";
                    body += "<td>" + (o["hACacidity"] == undefined ? "" : o["hACacidity"]) + "</td>";
                    body += "<td>" + (o["remark"] == undefined ? "" : o["remark"]) + "</td>";
                    body += "<td>" + o["createName"] + "</td>";
                    body += "<td>" + o["createTime"] + "</td>";
                    body += "<td>" + o["updateName"] + "</td>";
                    body += "<td>" + o["updateTime"] + "</td>";
                    body += "</tr>";
                })
                tableToXlsx(head, '导入中控中转检查站定义', body)
                console.log(table)
            }
        }

        function tableToXlsx(head: any, filename: any, body: any) {
            const uri = 'data:application/vnd.ms-excel;base64,',
                template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`;

            const a = document.createElement('a');
            a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
            a.download = filename;
            a.click();
            document.removeChild(a);
        }

        //模板下载
        const downloadHandler = () => {
            axios.get(baseURL + '/pdm/formulaDose/uploadModel', {
                responseType: 'blob',
                headers: {
                    token: sessionStorage.getItem('USER-TOKEN-KEY')
                }
            }).then((res) => {
                if (res.status === 200) {
                    filedownload(res.data, '导入中控中转检查站定义.xlsx')
                }
            })
        }
        //导入
        const importHandler = () => {

            const inputEle: HTMLInputElement = document.createElement('input')
            inputEle.type = 'file'
            inputEle.id = 'fileUploadExcel'
            inputEle.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
            inputEle.addEventListener('change', (e) => {
                const formData = new FormData()
                if (inputEle.files !== null) {
                    formData.append('file', inputEle.files[0] || '')
                } else {
                    Message.warning('未选择文件！');
                    return
                }
                pageData.pageLoading = true
                axios.post(baseURL + '/pdm/formulaDose/importModelData', formData, {
                    headers: {
                        "Content-Type": 'multipart/form-data',
                        "token": sessionStorage.getItem('USER-TOKEN-KEY')
                    },
                }).then((result) => {
                    if (result.data['code'] === 200) {
                        Message.success('导入成功')
                    } else {
                        Message.error(result.data.message)
                    }

                }).finally(() => {
                    pageData.pageLoading = false
                    doRefresh()
                })
            })
            inputEle.click()
        }
        // //设置权限
        // // ['查询', '新增', '删除', '导出', '导入']
        // const permissionStore = usePermission()

        // if (permissionStore.hasPermisson('ppzl.cx')) {

        //     pageData.btnList.push("查询")
        // }
        // if (permissionStore.hasPermisson('ppzl.xz')) {
        //     pageData.btnList.push("新增")
        // }
        // if (permissionStore.hasPermisson('ppzl.sc')) {
        //     pageData.btnList.push("删除")
        // }
        // if (permissionStore.hasPermisson('ppzl.dc')) {
        //     pageData.btnList.push("导出")
        // }
        // if (permissionStore.hasPermisson('ppzl.dr')) {
        //     pageData.btnList.push("导入")
        // }
        // if (permissionStore.hasPermisson('ppzl.xg')) {
        //     pageData.isEdit = true
        // }
        // console.log(permissionStore.hasPermisson('ppzl.cx'));
        const handleChange = (_data: any) => {
            table.handleSuccess(_data);
        }
        const defaultColDef = {
            sortable: true,
            resizable: true,
            filter: true,
            width: 450
        }
        emitter.on('shuaxiong', () => {
            doRefresh()
        })
        const audits = () => {
            if (gridOption.value.getSelectedRows().length === 0) {
                Message.error('请先勾选数据!')
                return;
            }
            var list: any = [];
            for (let i = 0; i < gridOption.value.getSelectedRows().length; i++) {
                var ob = {};
                ob["auditState"] = 1
                ob["id"] = gridOption.value.getSelectedRows()[i].id
                ob["formulaOdd"] = gridOption.value.getSelectedRows()[i].formulaOdd
                list.push(ob)
            }
            Modal.confirm({
                title: '系统提示',
                content: '是否审核此单号',
                onOk() {
                    post({
                        url: "/pdm/TransitInspect/updateAuditState",
                        data: list,
                    }).then((res: any) => {
                        if (res.code === 200) {
                            doRefresh();
                            Message.success('审核通过')
                        } else {
                            Message.error(res.message)
                        }
                    })
                }
            })

        }
        const localeText1: any = ref(localeText)
        const huiche = () => {
            doRefresh();
        }
        const pagingList1: any = ref(pagingList)
        const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('ImportCentralCheckpoint01', gridOption, colState01, tc)
        const onColumnMoved01 = () => {
            saveGridState01()
        }
        const onColumnResized01 = () => {
            saveGridState01()
        }

        const { saveGridState: saveGridState02, updateGridState: updateGridState02 } = saveOrUpdateGridState02('ImportCentralCheckpoint02', gridOption2, colState02, tc2)
        const onColumnMoved02 = () => {
            saveGridState02()
        }
        const onColumnResized02 = () => {
            saveGridState02()
        }
        return {
            saveOrUpdateGridState01,
            saveOrUpdateGridState02,
            saveGridState01,
            saveGridState02,
            updateGridState01,
            updateGridState02,
            onColumnMoved01,
            onColumnMoved02,
            onColumnResized01,
            onColumnResized02,
            colState01,
            colState02,
            pagingList1,
            huiche,
            audits,
            localeText1,
            editHandler,
            deleteHandler,
            sideOk,
            formRef,
            dataForm,
            addHandler,
            selectedRowKeys,
            pagination,
            tableColumns1,
            tableColumns2,
            table,
            rowKey,
            pageData,
            queryData,
            selectHandler,
            isChiese,
            inputBlur,
            exports,
            options,
            loading,
            handleSearch,
            focusSel,
            downloadHandler,
            importHandler,
            headerShow,
            handleChange,
            PageSize,
            change1,
            defaultColDef,
            tc,
            tc2,
            gridOption,
            gridOption2,
            gridReady,
            gridReady2,
            total,
            page,
            size,
            WHService,
        };
    },
    components: { Toolbar, PageTabelLayout,  }
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}
</style>